package Game5;

import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class TankMoveMsg implements Msg{
    int msgType=Msg.TANK_MOVE_MSG;
    int x,y;
    int id;
    Direction direction;
    GamePanel gp;
    public TankMoveMsg(int id,int x,int y,Direction direction) {
        this.id = id;
        this.x=x;
        this.y=y;
        this.direction=direction;
    }

    public TankMoveMsg(GamePanel gp) {
        this.gp = gp;
    }

    @Override
    public void send(DatagramSocket ds, String IP, int udpPort) {
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        DataOutputStream dos=new DataOutputStream(baos);
        try {
            dos.writeInt(msgType);
            dos.writeInt(id);
            dos.writeInt(x);
            dos.writeInt(y);
            dos.writeInt(direction.ordinal());
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[]buf= baos.toByteArray();
        try {
            DatagramPacket dp=new DatagramPacket(buf,buf.length,new InetSocketAddress(IP,udpPort));
            ds.send(dp);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void parse(DataInputStream dis) {
        try {
            int id= dis.readInt();
            if(gp.playerOne.id==id) {
                return;
            }
            int x= dis.readInt();
            int y=dis.readInt();
            Direction direction=Direction.values()[dis.readInt()];
            boolean  exist=false;
            for (int i=0;i<gp.tankList.size();i++) {
                Tank t=gp.tankList.get(i);
                if(t.id==id) {
                    t.x=x;
                    t.y=y;
                    t.direction=direction;
                    exist=true;
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
